#! /usr/bin/perl -w
package TaskManager;

use strict;
use Fcntl;
use DBUtility;

our $VERSION = 1.00;
our $STATUS_PTN = "Status: ";
our $COMMAND_PTN = "Command: ";
our $CAP_SEP = ":";

sub new{
   my ($class) = @_;
   my $self = {
      _host => undef,
      _dbutil => undef
   };
   bless $self;
   return $self;
}

sub init{
   my ($self, $host, $db, $username, $password) = @_; 

   $self->{_host} = $host;

   my $dbutil = new DBUtility();

   return 1 if($dbutil->init($host, $db, $username, $password));

   $self->{_dbutil} = $dbutil;

   return 0;
   
}
sub addTask{
   my ($self, $capabilities, $command,  $specified, $resource_id) = @_;
   return 1 unless defined($self->{_dbutil});
   
   #already specified the resource id
   if( $specified && defined($resource_id) )
   {
      #add the task to task table
	my $task = {
		rid => $resource_id,
		capabilities=>"\'$capabilities\'",
		stage=>0,
		status=>"\'scheduled\'",
		specified=>1,
		command=>"\'$command\'",
		createTime=>"CURRENT_TIMESTAMP"
	};
      #add the task to task table
      return $self->{_dbutil}->add_record("tasks", $task);
   }
   else
   {
      #find the suitable resource according to the capability requirements
	my @capability_list = split /$CAP_SEP/, $capabilities;

	my @requirement_list;
	foreach my $capability (@capability_list)
	{
		push @requirement_list, $capability." >= 0";
	}
	
	my $requirements = join(" AND ", @requirement_list);

	#here only query one row, TODO: change to query multiple rows and do selection
	my $hashref = $self->{_dbutil}->query("SELECT rid FROM capabilities WHERE $requirements");

	return 1 unless defined($hashref);

	my $task = {
		rid => $hashref->{rid},
		capabilities=>"\'$capabilities\'",
		stage=>0,
		status=>"\'scheduled\'",
		specified=>0,
		command=>"\'$command\'"
	};
      #add the task to task table
      return $self->{_dbutil}->add_record("tasks", $task);
   }   
}

